package com.bieyang.anjia.ui.adapter;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import com.bieyang.anjia.R;
import com.bieyang.anjia.module.Deviceinfo;
import com.bieyang.anjia.module.NewsInfo;
import com.bieyang.anjia.sqlitedatabase.AnjiaSQLiteOpenHelper;
import com.bieyang.anjia.sqlitedatabase.SqliteOperation;
import com.bieyang.anjia.utils.Constants;
import com.bieyang.anjia.utils.SubUtils;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

public class NewsAdapter extends BaseAdapter {
	private LayoutInflater inflater;
	View view;
	public TextView txtPlay, txtResetName, txtSetZhuji, txtRemove, txtjilu;
	int currentPosition;
	public ProgressDialog progressDialog;
	// private TAlarmSetInfor alarmInfo;
	public String imsi;
	Context con;
	List<NewsInfo> newsList;
	Deviceinfo devInfo;
	String uuid;
	SqliteOperation sqlOperation;
	Handler handler = new Handler();

	public NewsAdapter(Context con) {
		this(con, new ArrayList<NewsInfo>());
	}

	public NewsAdapter(Context con, List<NewsInfo> newsList) {
		this.newsList = newsList;
		this.con = con;
		if (null == sqlOperation) {
			sqlOperation = new SqliteOperation(con,
					AnjiaSQLiteOpenHelper.dbName, AnjiaSQLiteOpenHelper.version);
		}
		inflater = LayoutInflater.from(con);
	}

	public List<NewsInfo> getNewsList() {
		return newsList;
	}

	public void setNewsList(List<NewsInfo> newsList) {
		this.newsList = newsList;
		notifyDataSetChanged();
	}

	@Override
	public int getCount() {
		return newsList.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		ViewHolder holder;
		if (convertView == null) {
			convertView = inflater.inflate(R.layout.news_item, null);
			holder = new ViewHolder(convertView);
			holder.tvCaption.setOnClickListener(new OnClickListstener(
					holder.tvCaption, position));
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		NewsInfo newsInfo = newsList.get(position);
		setImg(newsInfo, position, holder.imgNews);
		int black = con.getResources().getColor(R.color.front_black);
		int gray = con.getResources().getColor(R.color.gray);
		int grey = con.getResources().getColor(R.color.grey);
		if ("T".equals(newsInfo.isnew)) {
			holder.tvCaption.setTextColor(black);
			holder.tvContent.setTextColor(gray);
			holder.tvTime.setTextColor(gray);
		} else {
			holder.tvCaption.setTextColor(gray);
			holder.tvContent.setTextColor(grey);
			holder.tvTime.setTextColor(grey);
		}
		holder.tvCaption.setText(newsInfo.title);
		if (!("".equals(newsInfo.content) || "null".equals(newsInfo.content)))
			holder.tvContent.setText(newsInfo.content + "……");
		holder.tvTime.setText(newsInfo.submitTime);
		Log.e("submitTime", newsInfo.submitTime + "----");
		return convertView;
	}

	/**
	 * 设置资讯图片
	 * 
	 * @param newsInfo
	 *            资讯模型
	 * @param position
	 *            位置
	 * @param img
	 */
	private void setImg(NewsInfo newsInfo, int position, ImageView img) {
		if (null == newsInfo.picturePath || "null".equals(newsInfo.picturePath)) {
			newsInfo.picturePath = sqlOperation.query("newsinfo",
					"picturepath", "newsid = ?", new String[] { newsInfo.newsId
							+ "" });
			if (null == newsInfo.picturePath
					|| TextUtils.equals("null", newsInfo.picturePath)) {
				downLoadImg(newsInfo, position, img);
			} else {
				if (imgExists(newsInfo.picturePath)) {
					img.setImageURI(Uri.parse(newsInfo.picturePath));
				} else {
					downLoadImg(newsInfo, position, img);
				}
			}
		} else {
			if (imgExists(newsInfo.picturePath)) {
				img.setImageURI(Uri.parse(newsInfo.picturePath));
			} else {
				downLoadImg(newsInfo, position, img);
			}
		}
	}

	/**
	 * 判断文件是否存在
	 * 
	 * @param path
	 *            路径
	 * @return
	 */
	private boolean imgExists(String path) {
		File file = new File(path);
		return file.exists();
	}

	/**
	 * 下载文件
	 * 
	 * @param newsInfo
	 *            资讯模型
	 * @param position
	 *            位置
	 * @param img
	 */
	private void downLoadImg(NewsInfo newsInfo, int position, ImageView img) {
		if (null == newsInfo.pictureUrl
				|| TextUtils.equals("null", newsInfo.pictureUrl)) {
			img.setImageResource(R.drawable.camera);
		} else {
			downLoad(position, newsInfo.newsId, newsInfo.pictureUrl, img);
		}

	}

	/**
	 * 文件下载
	 * 
	 * @param url
	 *            路径
	 * @param map
	 * @param position
	 *            list偏移量
	 */
	@SuppressLint("SimpleDateFormat")
	private void downLoad(final int position, final int id, final String url,
			final ImageView imageView) {
		System.out.println("downLoad");
		System.out.println(url);
		new Thread(new Runnable() {
			@Override
			public void run() {
				Looper.prepare();
				HttpClient httpClient = new DefaultHttpClient();
				// GET
				HttpGet myGet = new HttpGet(url);
				try {
					HttpResponse response = httpClient.execute(myGet);
					String fileName = id + "news";
					String dir = new SubUtils().getFileFloderPath(con) + "news"
							+ File.separator;
					File file = new File(dir);
					if (!file.exists()) {
						file.mkdirs();
					}
					final String filepath = dir + fileName
							+ Constants.PICTURE_SUFFIX;
					File childFile = new File(filepath);
					FileOutputStream fileout = new FileOutputStream(childFile);
					InputStream is = response.getEntity().getContent();
					byte[] buffer = new byte[1024];
					int ch = 0;
					while ((ch = is.read(buffer)) != -1) {
						fileout.write(buffer, 0, ch);
					}
					is.close();
					fileout.flush();
					fileout.close();
					handler.post(new Runnable() {

						@Override
						public void run() {
							imageView.setImageURI(Uri.parse(filepath));
							NewsInfo newsInfo = newsList.get(position);
							newsInfo.picturePath = filepath;
							sqlOperation.update("newsinfo", "newsid = ?",
									new String[] { newsInfo.newsId + "" },
									"picturepath", filepath);
							imageView.postInvalidate();
						}
					});
				} catch (Exception e) {
				}
				Looper.loop();
			}
		}).start();

	}

	public class ViewHolder {
		ImageView imgNews;
		TextView tvCaption;
		TextView tvContent;
		TextView tvTime;

		public ViewHolder(View view) {
			// TODO Auto-generated constructor stub
			imgNews = (ImageView) view.findViewById(R.id.imgNews);
			tvCaption = (TextView) view.findViewById(R.id.tvCaption);
			tvContent = (TextView) view.findViewById(R.id.tvContent);
			tvTime = (TextView) view.findViewById(R.id.tvTime);

		}
	}

	public class OnClickListstener implements OnClickListener {
		int position;
		ImageView imgaArrow;
		TextView tvCaption;
		View v;

		public OnClickListstener(int position) {
			this.position = position;
		}

		public OnClickListstener(View v, int position3) {
			// TODO Auto-generated constructor stub
			this.position = position3;
			this.v = v;

		}

		@Override
		public void onClick(View v) {
			// con.startActivity(new Intent(con,AlarmSetActivity.class));
			switch (v.getId()) {

			// case R.id.tvCaption:
			// con.startActivity(new Intent(con,AlarmSetActivity.class));
			// break;
			default:
				break;
			}

		}

	}

	void resetName() {
		View view = LayoutInflater.from(con).inflate(
				R.layout.layout_modify_name, null);
		final EditText input = (EditText) view.findViewById(R.id.edit_add_dir);
		TextView txtname = (TextView) view.findViewById(R.id.txt_add_dir);
		txtname.setText(con.getString(R.string.modify_name));
		new AlertDialog.Builder(con)
				.setTitle(con.getString(R.string.modify_name))
				.setView(view)
				.setPositiveButton(con.getString(R.string.positive),
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								progressDialog.show();
								new Thread() {

									@Override
									public void run() {
										// TODO Auto-generated method stub
										final String dirName = input.getText()
												.toString();
										if (TextUtils.isEmpty(dirName)) {
											// handler.sendEmptyMessage(ADD_DIR_FIALED);
											return;
										}
									}
								}.start();
							}
						})
				.setNegativeButton(con.getString(R.string.negative), null)
				.show();

	}

}
